package com.envper.controller.user;

import com.envper.common.domain.dto.UserDto;
import com.envper.mysql.domain.Result;
import com.envper.mysql.domain.Status;
import com.envper.mysql.domain.vo.UserVo;
import com.envper.common.exception.GlobalException;
import com.envper.common.service.UserService;
import com.envper.common.util.IdUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RequiredArgsConstructor
@RequestMapping("/user")
@RestController
@Tag(name = "用户接口")
@SecurityRequirement(name = "bearerAuth")
public class UserController {
    private final UserService userService;
    private final IdUtils idUtils;

    @GetMapping("/info")
    @Operation(summary = "获取用户信息", description = "根据用户ID获取用户信息")
    public Result<UserDto> getUserInfo(@RequestParam(value = "userId", required = false) Long userId) {
        if(ObjectUtils.isEmpty(userId)) userId = idUtils.getUserIdByRequest();
        UserDto userDto = userService.getUserInfoById(userId);
        return Result.ok(Status.SUCCESS, userDto);
    }

    @GetMapping("/info/list")
    public Result<List<UserDto>> getUserInfoList() {
        List<UserDto> userInfoList = userService.getUserInfoList();
        return Result.ok(Status.SUCCESS, userInfoList);
    }

    @GetMapping("/list")
    public Result<List<UserVo>> getUserList() {
        List<UserVo> userList = userService.getUserList();
        return Result.ok(Status.SUCCESS, userList);
    }

    @GetMapping("/list/search")
    public Result<List<UserVo>> searchUserList(@RequestParam("keyword") String keyword) {
        List<UserVo> userList = userService.searchUserList(keyword);
        return Result.ok(Status.SUCCESS, userList);
    }

    @DeleteMapping("/delete")
    public Result<String> deleteUser(@RequestParam("userId") Long userId) {
        if(ObjectUtils.isEmpty(userId)) throw new GlobalException(Status.PARAMERROR);
        userService.deleteUserByUserId(userId);
        return Result.ok(Status.DELETESUCCESS);
    }

    @PutMapping("/password/edit")
    public Result<String> editUserPassword(@RequestBody UserDto userDto) {
        userService.editUserPasswordByUserId(userDto);
        return Result.ok(Status.EDITSUCCESS);
    }

    @PutMapping("/info/edit")
    public Result<String> editUserInfo(@RequestBody UserDto userDto) {
        userService.editUserInfoByUserId(userDto);
        return Result.ok(Status.EDITSUCCESS);
    }

    @PostMapping("/avatar/upload")
    public Result<String> uploadAvatar(@RequestParam("avatar") MultipartFile avatar) {
        userService.uploadAvatar(avatar);
        return Result.ok(Status.UPLOADSUCCESS);
    }
}
